package com.dense.kuiniu.bookborrow.business.home.common;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dense.kuiniu.bookborrow.R;
import com.dense.kuiniu.bookborrow.base.BaseFragment;
import com.dense.kuiniu.bookborrow.base.Url;
import com.dense.kuiniu.bookborrow.business.adapter.NumberAdapter;
import com.dense.kuiniu.bookborrow.business.entity.NumberBean;
import com.dense.kuiniu.bookborrow.business.entity.Reader;
import com.dense.kuiniu.bookborrow.utils.MD5Utils;
import com.dense.kuiniu.bookborrow.view.CountDownView;
import com.dense.kuiniu.bookborrow.view.CounterController;
import com.dense.kuiniu.bookborrow.view.dialog.CommonDialog;
import com.rxjava.rxlife.RxLife;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.disposables.Disposable;
import rxhttp.RxHttp;

/**
 * @author Administrator
 * @date 2020/8/25
 */
public class PasswordDelegate extends BaseFragment {
    private static final String ACCOUNT = "account";
    private static final String AUTHENTICATION = "authentication";

    public static PasswordDelegate getInstance(String account, Authentication authentication) {
        Bundle bundle = new Bundle();
        bundle.putString(ACCOUNT, account);
        bundle.putParcelable(AUTHENTICATION, authentication);
        PasswordDelegate delegate = new PasswordDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.et_search)
    EditText mEditText;
    @BindView(R.id.count_down_view)
    CountDownView mCountDownView;
    private String mAccount;
    private CommonDialog mDialog;
    private Disposable mDisposable;

    private Authentication mAuthentication;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mAccount = bundle.getString(ACCOUNT);
            mAuthentication = bundle.getParcelable(AUTHENTICATION);
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.delegate_input_password;
    }

    @Override
    protected void init() {
        if (getActivity() != null) {
            mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
            NumberAdapter adapter = new NumberAdapter(R.layout.item_number, makeData());
            mRecyclerView.setAdapter(adapter);
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    NumberBean numberBean = (NumberBean) adapter.getItem(position);
                    String pwd = mEditText.getText().toString();
                    if (numberBean != null) {
                        switch (numberBean.getType()) {
                            case 0:
                                mEditText.append(numberBean.getName());
                                break;
                            case 1:
                                if (pwd.length() > 0) {
                                    pwd = pwd.substring(0, pwd.length() - 1);
                                    mEditText.setText(pwd);
                                }
                                break;
                            case 2:
                                if (!pwd.isEmpty()) {
                                    confirm(pwd);
                                }
                                break;
                        }
                    }
                }
            });
        }
        mCountDownView.start(new CounterController.OnCompleteListener() {
            @Override
            public void onComplete() {
                exit();
            }
        });
    }

    @OnClick({R.id.tv_exit})
    public void onClick(View view) {
        super.onClick(view);
    }

    @Override
    protected void onClick2(View view) {
        int id = view.getId();
        if (id == R.id.tv_exit) {
            exit();
        }
    }


    private List<NumberBean> makeData() {
        List<NumberBean> list = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            list.add(new NumberBean(0, String.valueOf(i)));
        }
        list.add(new NumberBean(1, getString(R.string.text_delete)));
        list.add(new NumberBean(0, String.valueOf(0)));
        list.add(new NumberBean(2, getString(R.string.text_confirm)));
        return list;
    }

    private void confirm(String password) {
        showLoading();
        mDisposable = RxHttp.postJson(Url.identityAuthentication)
                .add("account", mAccount)
                .add("password", MD5Utils.digest(password))
                .asResponse(Reader.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(reader -> {
                    if ("正常".equals(reader.getVuserInfo().getState())) {
                        stopLoading();
                        if (mAuthentication != null) {
                            mAuthentication.succeed(PasswordDelegate.this, reader);
                        }
                    } else {
                        showReaderStatusError(reader.getVuserInfo().getState());
                    }

                }, throwable -> {
                    mDialog.error(throwable.getMessage());
                    // stopLoading2();
                });
    }

    private void showLoading() {
        if (mDialog == null) {
            mDialog = new CommonDialog(getActivity());
        }
        mDialog.confirm(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                if (mDisposable != null && !mDisposable.isDisposed()) {  //判断请求有没有结束
                    mDisposable.dispose();       //没有结束，则关闭请求
                }
            }
        }).loading(getString(R.string.text_Certification_in_progress)).show();
    }

    public void showReaderStatusError(String msg) {
        mDialog.error(getString(R.string.text_account_unusual) + msg + getString(R.string.text_deal_error));
        mDialog.confirm(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                pop();
            }
        });
    }


    private void stopLoading2() {
        //  mSweetAlertDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
        // mSweetAlertDialog.setCustomImage(R.mipmap.ic_error);
    }

    private void stopLoading() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    private void exit() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        pop();
    }
} 